<template>
  <div class="pagination">
    <button
      :disabled="startEndPage.start === 1"
      @click="changepageNo(pageNo - 1)"
    >
      上一页
    </button>
    <button v-show="startEndPage.start > 1" @click="changepageNo(1)">1</button>

    <button v-show="startEndPage.start > 2">···</button>

    <button
      v-for="item in startEndArr"
      :class="{ active: pageNo === item }"
      :key="item"
      @click="changepageNo(item)"
    >
      {{ item }}
    </button>

    <button v-show="startEndPage.end < totalPages - 1">···</button>
    <button
      v-show="startEndPage.end < totalPages"
      @click="changepageNo(totalPages)"
    >
      {{ totalPages }}
    </button>
    <button
      :disabled="startEndPage.end === totalPages"
      @click="changepageNo(pageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["pageNo", "totalPages", "total", "continuePage"],
  computed: {
    //计算连续值的开始值和结束值
    startEndPage() {
      const { pageNo, totalPages, continuePage } = this;
      let start = 0;
      let end = 0;
      //如果总页数小于continue,start=1,end=总页数
      if (totalPages < continuePage) {
        (start = 1), (end = totalPages);
      } else {
        start = pageNo - Math.floor(continuePage / 2);
        end = pageNo + Math.floor(continuePage / 2);
        if (start < 1) {
          (start = 1), (end = continuePage);
        }
        if (end > totalPages) {
          (end = totalPages), (start = totalPages - continuePage + 1);
        }
      }
      return { start, end };
    },
    //计算连续值遍历的数组
    startEndArr() {
      let arr = [];
      for (var i = this.startEndPage.start; i <= this.startEndPage.end; i++) {
        arr.push(i);
      }
      return arr;
    },
  },
  methods: {
    //点击更改pageNo
    changepageNo(page) {
      this.$emit("changePageNoHandler", page);
      // console.log(page);
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
